package com.lap.auth.adapter.driving.persistence.role.repository;

import com.lap.auth.adapter.driving.persistence.role.RoleCache;
import com.lap.auth.adapter.driving.persistence.role.RoleConverter;
import com.lap.auth.adapter.driving.persistence.role.mapper.RoleDataScopeMapper;
import com.lap.auth.adapter.driving.persistence.role.po.RoleDataScopePo;
import com.lap.auth.domain.role.repository.RoleDataScopeRepository;
import com.lap.auth.domain.role.valueobject.RoleDataScope;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class RoleDataScopeRepositoryImpl implements RoleDataScopeRepository {

  private final RoleConverter roleConverter;
  private final RoleDataScopeMapper roleDataScopeMapper;

  @CacheEvict(value = RoleCache.ROLE_DATA_SCOPE, key = "#roleDataScope.roleId()")
  @Override
  public void save(RoleDataScope roleDataScope) {
    RoleDataScopePo roleDataScopePo = roleConverter.toDataScopePo(roleDataScope);
    roleDataScopeMapper.insert(roleDataScopePo);
  }

  @CacheEvict(value = RoleCache.ROLE_DATA_SCOPE, key = "#roleId")
  @Override
  public int deleteByRoleId(Integer roleId) {
    return roleDataScopeMapper.deleteByRoleId(roleId);
  }

  @Override
  public Optional<RoleDataScope> findByRoleId(Integer roleId) {
    RoleDataScopePo po = roleDataScopeMapper.selectByRoleId(roleId);
    return Optional.ofNullable(roleConverter.toScopeDomain(po));
  }

  @Cacheable(
      value = RoleCache.ROLE_DATA_SCOPE,
      key = "T(com.lap.auth.domain.shared.tools.CacheKeyUtil).generateKey(#roleIds)")
  @Override
  public List<RoleDataScope> findByRoleIds(List<Integer> roleIds) {
    List<RoleDataScopePo> sources = roleDataScopeMapper.selectByRoleIds(roleIds);
    return roleConverter.toScopeDomains(sources);
  }
}
